<!--
 * @Author: 137 '1432417996@qq.com'
 * @Date: 2025-04-16 22:42:32
 * @LastEditors: 137 '1432417996@qq.com'
 * @LastEditTime: 2025-04-23 00:38:28
 * @FilePath: \starter-3\pages\information\informationDetails.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->

<template>
  <div class="information-content">
    <!-- 顶部宣传图片 -->
    <div class="top-banner mb-2 mt-2 rounded-lg overflow-hidden relative shadow-md" @click="goAd(contentTopAd)"
      v-if="contentTopAd.adImageUrl">
      <img :src="contentTopAd.adImageUrl" :alt="contentTopAd.adDescription" class="w-full h-[180px] object-fill">
      <div class="right-a-tag" v-if="contentTopAd.showAdTag">广告</div>
    </div>

    <!-- 面包屑导航 -->
    <div class="breadcrumb flex items-center mb-2 py-1 text-sm text-gray-500">
      <a href="/" class="text-gray-600 hover:text-primary transition-colors flex items-center">首页</a>
      <el-icon class="mx-2 text-xs">
        <ArrowRight />
      </el-icon>
      <a href="/information/informationList"
        class="text-gray-600 hover:text-primary transition-colors flex items-center">出海头条</a>
      <el-icon class="mx-2 text-xs">
        <ArrowRight />
      </el-icon>
      <span class="text-gray-900 font-medium">正文</span>
    </div>

    <div class="content-wrapper grid grid-cols-1 lg:grid-cols-3 gap-4">
      <main class="lg:col-span-2">
        <article class="bg-white rounded-lg shadow-md p-6">
          <div class="article-header mb-6 pb-4 border-b border-gray-200">
            <h1 class="article-title text-2xl font-semibold mb-4 text-gray-900">{{ newsDetail.title }}</h1>
            <div
              class="article-meta flex flex-col sm:flex-row justify-between items-start sm:items-center flex-wrap gap-4 mb-2">
              <div class="article-author flex items-center gap-4">
                <div class="author-avatar w-12 h-12 rounded-full overflow-hidden border-2 border-primary/20"
                  style="flex-shrink: 0;">
                  <img :src="newsDetail.creatorAvatar" :alt="newsDetail.creatorName" class="w-full h-full object-fill">
                </div>
                <div class="author-info flex flex-col">
                  <div class="author-name font-semibold text-gray-900">
                    <div @click="goUserPage">{{ newsDetail.creatorName }}</div>
                  </div>
                  <div class="author-title text-xs text-gray-500">{{ newsDetail.creatorSignature }}</div>
                </div>
                <el-button type="primary" @click="followAuthor">{{ followAuthorStatus ? '已关注' : '+关注' }}</el-button>
              </div>
              <div class="article-stats flex items-center gap-6">
                <div class="article-stat flex items-center gap-1 text-gray-500 text-sm">
                  <el-icon>
                    <Clock />
                  </el-icon>
                  <span>
                    <DateConvert :date="newsDetail.publishTime" />
                  </span>
                </div>
                <div class="article-stat flex items-center gap-1 text-gray-500 text-sm">
                  <el-icon>
                    <View />
                  </el-icon>
                  <span>{{ newsDetail.viewCount }}</span>
                </div>
              </div>
            </div>

            <!-- 广告位 -->
            <div v-if="articleInnerAd.adImageUrl" @click="goAd(articleInnerAd)"
              class="bg-orange-50 rounded-lg p-4 mt-4 border-l-4 border-orange-500 text-sm cursor-pointer inner-a">
              <div class="text-orange-500 font-medium hover:underline">{{ articleInnerAd.adDescription }}</div>
              <div class="right-a-tag" v-if="articleInnerAd.showAdTag">广告</div>
            </div>
          </div>

          <!-- 文章内容 -->
          <div class="article-content text-base leading-relaxed relative">
            <div v-html="newsDetail.content"></div>
            <el-tag style="margin-left: 5px;" v-for="tag in tagsBtn" :key="tag" type="info">{{ tag }}</el-tag>
            <!-- 文章互动功能 -->
            <div class="article-tool article-interaction flex justify-between items-center py-4 mt-4">
              <div class="article-actions article-tool-box flex gap-4">
                <div class="tool-btn blue-btn" :class="{ 'active': newsDetail.isLike }" @click="toggleLikeFun('like')">
                  <i class="zan-icon" :class="{ 'active': newsDetail.isLike }"></i>
                  <span class="action-count font-medium">{{ newsDetail.likeCount > 999 ? '999+' : newsDetail.likeCount
                  }}</span>
                </div>
                <div class="tool-btn red-btn" :class="{ 'active': newsDetail.isUnlike }"
                  @click="toggleLikeFun('unlike')">
                  <i class="cai-icon" :class="{ 'active': newsDetail.isUnlike }"></i>
                  <span class="action-count font-medium">{{ newsDetail.unlikeCount > 999 ? '999+' :
                    newsDetail.unlikeCount
                    }}</span>
                </div>
                <div class="tool-btn yellow-btn" :class="{ 'active': newsDetail.isFavorite }"
                  @click="toggleLikeFun('favorite')">
                  <el-icon>
                    <Star />
                  </el-icon>
                  <span class="action-count font-medium">{{ newsDetail.favoriteCount > 999 ? '999+' :
                    newsDetail.favoriteCount }}</span>
                </div>
              </div>

            </div>
          </div>
        </article>
        <!-- 底部广告 -->
        <div class="mb-6 mt-6 gap-2 footer-carousel-box">
          <div class="footer-carousel-container" ref="footerCarouselContainer">
            <div class="footer-carousel-wrapper" ref="footerCarouselWrapper">
              <div class="footer-carousel" @click="goAd(item)" v-for="(item, index) in displayAds" :key="index">
                <img :src="item.adImageUrl" :alt="item.adDescription" class="w-full aspect-video object-fill">
                <div class="right-a-tag" v-if="item.showAdTag">广告</div>
              </div>
            </div>
          </div>
        </div>
      </main>

      <!-- 侧边栏 -->
      <aside class="sidebar flex flex-col gap-4">
        <!-- 媒体信息卡片 -->
        <section class="media-card bg-white rounded-lg shadow-md overflow-hidden">
          <div class="media-card-header flex items-center justify-center p-4 bg-gray-50 border-b border-gray-100">
            <div class="media-logo w-20 h-20 flex items-center justify-center">
              <img :src="newsAuthor.avatar" :alt="newsAuthor.nickName"
                class="max-w-full max-h-full rounded-full object-fill">
            </div>
          </div>
          <div class="media-card-content p-4 text-center">
            <h3 class="media-name text-lg font-semibold mb-2 text-gray-900">{{ newsAuthor.nickName }}</h3>
            <p class="media-description text-sm text-gray-600 mb-4 leading-relaxed">{{ newsAuthor.personalSignature }}
            </p>
            <div class="media-stats flex justify-center gap-4 mb-4">
              <div class="media-stat flex flex-col items-center">
                <div class="stat-value text-base font-semibold text-gray-900">{{ newsAuthor.totalNews }}</div>
                <div class="stat-label text-xs text-gray-500">文章数</div>
              </div>
              <div class="media-stat flex flex-col items-center">
                <div class="stat-value text-base font-semibold text-gray-900">{{ newsAuthor.totalNews }}</div>
                <div class="stat-label text-xs text-gray-500">阅读量</div>
              </div>
            </div>
            <div class="media-actions flex justify-center gap-2.5">
              <el-button type="primary" @click="followAuthor">{{ followAuthorStatus ? '已关注' : '+关注' }}</el-button>
              <el-button type="info" @click="contactAuthor" v-if="false">立即联系</el-button>
            </div>
          </div>
        </section>

        <!-- 热门文章 -->
        <section class="sidebar-section bg-white rounded-lg shadow-md overflow-hidden">
          <h2
            class="sidebar-title text-lg font-semibold p-4 pt-2 pb-0 bg-primary/10 text-gray-900 flex items-center gap-2">
            <el-icon class="text-primary" color="#007bff">
              <Star />
            </el-icon>
            热门文章
          </h2>
          <div v-for="item in hotArticles" :key="item.id" @click="goDetails(item.id)"
            class="hot-article flex gap-4 px-4 py-2 border-b border-gray-200 transition-colors hover:bg-primary/5">
            <div class="hot-article-image w-20 h-15 rounded overflow-hidden flex-shrink-0">
              <img :src="item.coverImageUrl" :alt="item.title" class="w-full h-full object-cover">
            </div>
            <div class="hot-article-content flex-1 flex flex-col justify-between">
              <h4 class="text-sm leading-relaxed font-medium line-clamp-2 mb-1">{{ item.title }}</h4>
              <div class="hot-article-meta flex items-center gap-1 text-gray-500 text-xs">
                <el-icon>
                  <View />
                </el-icon>
                <span>{{ item.viewCount }}</span>
              </div>
            </div>
          </div>
        </section>

        <!-- 推荐广告 -->
        <section v-for="item in sidebarAd" :key="item.id"
          @click="goAd(item)"
          class="sidebar-section bg-white rounded-lg shadow-md overflow-hidden">
          <div class="recommend-ads">
            <div class="relative">
              <img :src="item.adImageUrl" :alt="item.adDescription" class="aspect-video w-full">
              <div class="right-a-tag" v-if="item.showAdTag">广告</div>
            </div>
          </div>
        </section>
      </aside>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import {
  getNewsAdList, getNewsAuthor, getNewsHot,
  getNewsDetail, getNewsAdClick, getNewsAction
} from "@/api/information";

import { checkUserAction, performUserAction } from "@/api/userAction";

import { useRoute, useRouter } from "vue-router";
import { View, Star, ArrowRight } from '@element-plus/icons-vue';
const router = useRouter()
const route = useRoute()
const newsId = ref(route.query.id)



// 分享功能
const showShareDropdown = ref(false);

const followAuthorStatus = ref(false);
// 关注作者
const followAuthor = () => {
  performUserAction({
    targetId: newsAuthor.value.userId,
    businessType: 'user',
    actionType: 'follow'
  }).then(res => {
    // console.log(res);
    //followAuthorStatus.value = res.data;
    checkUserActionFunFollow();
  })
}

const userStore = useUserStore();


const footerCarouselContainer = ref(null);
const footerCarouselWrapper = ref(null);
let currentIndex = 0;
let autoScrollInterval = null;

const displayAds = computed(() => {
    if (contentBottomAd.value.length <= 3) return contentBottomAd.value;
    
    // 在列表前后各添加广告项，实现无缝滚动
    // 前面添加最后两个广告项
    // 后面添加前两个广告项
    return [
        contentBottomAd.value[contentBottomAd.value.length - 2],
        contentBottomAd.value[contentBottomAd.value.length - 1],
        ...contentBottomAd.value,
        contentBottomAd.value[0],
        contentBottomAd.value[1]
    ];
});

const startAutoScroll = () => {
    if (contentBottomAd.value.length <= 3) return;
    
    // 先清除之前的定时器
    stopAutoScroll();
    
    // 初始位置设置为第二个广告（跳过前面添加的重复项）
    currentIndex = 2;
    if (footerCarouselWrapper.value) {
        footerCarouselWrapper.value.style.transform = `translateX(${-currentIndex * (100 / 3)}%)`;
    }
    
    autoScrollInterval = setInterval(() => {
        currentIndex = (currentIndex + 1) % (contentBottomAd.value.length + 4);
        const translateX = -currentIndex * (100 / 3);
        
        if (footerCarouselWrapper.value) {
            footerCarouselWrapper.value.style.transform = `translateX(${translateX}%)`;
            
            // 当滚动到倒数第二个时，立即跳转到第二个（视觉上无感知）
            if (currentIndex === contentBottomAd.value.length + 2) {
                setTimeout(() => {
                    currentIndex = 2;
                    footerCarouselWrapper.value.style.transition = 'none';
                    footerCarouselWrapper.value.style.transform = `translateX(${-currentIndex * (100 / 3)}%)`;
                    // 强制重排，确保样式更新
                    footerCarouselWrapper.value.offsetHeight;
                    footerCarouselWrapper.value.style.transition = 'transform 0.5s ease';
                }, 500);
            }
        }
    }, 3000);
}

const stopAutoScroll = () => {
    if (autoScrollInterval) {
        clearInterval(autoScrollInterval);
        autoScrollInterval = null;
    }
}

onMounted(() => {

  getNewsAdListFun();
  getNewsDetailFun();
  getNewsAdClickFun();
  getNewsHotFun();
  // 确保DOM更新后再设置初始位置
  nextTick(() => {
        if (contentBottomAd.value.length > 3) {
            currentIndex = 2;
            if (footerCarouselWrapper.value) {
                footerCarouselWrapper.value.style.transition = 'none';
                footerCarouselWrapper.value.style.transform = `translateX(${-currentIndex * (100 / 3)}%)`;
                footerCarouselWrapper.value.offsetHeight;
                footerCarouselWrapper.value.style.transition = 'transform 0.5s ease';
            }
        }
    });
});

onUnmounted(() => {
    stopAutoScroll();
})

// 获取热门文章
const hotArticles = ref([]);
const getNewsHotFun = () => {
  getNewsHot().then(res => {
    hotArticles.value = res.data;
  })
}

// 增加点击次数
const getNewsAdClickFun = () => {
  getNewsAdClick({ adId: newsId.value }).then(res => {
    console.log(res);
  })
}

const newsAuthor = ref({});

// 获取作者信息
const getNewsAuthorFun = () => {
  getNewsAuthor(newsDetail.value.creatorId).then(res => {
    console.log(res);
    newsAuthor.value = res.data;
    if (userStore.token) {
      checkUserActionFunFollow();
    }
  })
}

// 检查是否关注作者
const checkUserActionFunFollow = () => {
  checkUserAction({
    targetId: newsAuthor.value.userId,
    businessType: 'user',
    actionType: 'follow'
  }).then(res => {
    console.log(res);
    followAuthorStatus.value = res.data;
  })
}

// 轮播图数据
const carouselSlidesTop = ref([]);
const contentTopAd = ref({});
const articleInnerAd = ref({});
const contentBottomAd = ref([]);
const sidebarAd = ref([]);
const getNewsAdListFun = () => {
  getNewsAdList().then(res => {
    console.log(res);
    carouselSlidesTop.value = [];
    contentTopAd.value = {};
    articleInnerAd.value = {};
    contentBottomAd.value = [];
    sidebarAd.value = [];
    res.data.forEach(item => {
      if (item.adPosition === 'home_top') {
        carouselSlidesTop.value.push(item)
      }
      if (item.adPosition === 'content_top' && !contentTopAd.value.id) {
        contentTopAd.value = item;
      }
      if (item.adPosition === 'footer_carousel') {
        contentBottomAd.value.push(item);
      }
      if (item.adPosition === 'sidebar') {
        if (!sidebarAd.value.length < 3) {
          sidebarAd.value.push(item);
        }
      }
      if (item.adPosition === 'article_inner' && !articleInnerAd.value.id) {
        articleInnerAd.value = item;
      }

    })
     // 确保DOM更新后再启动自动滚动
     nextTick(() => {
            startAutoScroll();
        });
  })
}

// 执行用户行为
const toggleLikeFun = (type) => {
  performUserAction({
    targetId: newsId.value,
    businessType: 'news',
    actionType: type
  }).then(res => {
    if (type === 'like') {
      newsDetail.value.likeCount += 1;
    }
    if (type === 'unlike') {
      newsDetail.value.unlikeCount += 1
    }
    console.log(res);
    getNewsDetailFun();
  })
}

// 检查用户行为
const checkUserActionFun = () => {
  checkUserAction({
    targetId: newsId.value,
    businessType: 'news',
    actionType: type
  }).then(res => {
    console.log(res);
  })
}

// 获取文章详情
const newsDetail = ref({ isFavorite: false, isLike: false, isUnlike: false });
const tagsBtn = ref([]);
const getNewsDetailFun = () => {
  getNewsDetail(newsId.value).then(res => {
    console.log(res);
    newsDetail.value = res.data;
    tagsBtn.value = newsDetail.value.tags?.split(',');
    getNewsAuthorFun();
  })
}


const goDetails = (id) => {
  const targetRoute = router.resolve({ path: '/information/informationDetails', query: { id } });
  window.open(targetRoute.href, '_blank');
}

const goAd = (item) => {
  window.open(item.jumpUrl, '_blank');
}
</script>

<style scoped>
.no-scroll {
  overflow: hidden;
}

.active {
  color: var(--el-color-primary);
}


.action-btn.active {
  background-color: var(--el-color-primary-light-9);
  border-color: var(--el-color-primary);
  color: var(--el-color-primary);
}

.action-btn.dislike.active {
  background-color: #ffeeee;
  border-color: #ff4d4f;
  color: #ff4d4f;
}

.action-btn.collected {
  background-color: #fff7e6;
  border-color: #faad14;
  color: #faad14;
}

.tooltip.show {
  opacity: 1;
}

.image-viewer-overlay.active {
  opacity: 1;
}

@media (max-width: 1024px) {
  .content-wrapper {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .article-meta {
    flex-direction: column;
    align-items: flex-start;
  }

  .article-stats {
    width: 100%;
    justify-content: flex-start;
  }

  .image-viewer-prev,
  .image-viewer-next {
    position: absolute;
    top: 50%;
    width: 40px;
    height: 40px;
    font-size: 16px;
  }

  .image-viewer-prev {
    left: 10px;
  }

  .image-viewer-next {
    right: 10px;
  }

  .image-viewer-img {
    max-height: 75%;
  }

  .image-viewer-caption {
    font-size: 14px;
    padding: 8px 0;
  }
}

@media (max-width: 480px) {
  .article-title {
    font-size: 24px;
  }

  .article-lead {
    font-size: 16px;
  }

  .article {
    padding: 16px;
  }

  .article-author {
    flex-wrap: wrap;
  }

  .follow-btn {
    margin-left: 0;
    margin-top: 4px;
  }
}

.footer-carousel-box {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  position: relative;
    overflow: hidden;
}

.footer-carousel-container {
    width: 100%;
    overflow: hidden;
}

.footer-carousel-wrapper {
    display: flex;
    transition: transform 0.5s ease;
    gap: 11px;
    width: 100%;
}

.footer-carousel {
  border-radius: 10px;
  width: calc(33.33% - 10px);
  height: 100px;
  position: relative;
  overflow: hidden;
  flex-shrink: 0;
}

.inner-a {
  position: relative;
}

.article-tool {
  position: absolute;
  top: 0;
  left: -80px;
  right: 0;

  .article-tool-box {
    flex-direction: column;
  }

  .tool-btn {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f8f8fa;
    color: #aaa;
    border: 1px solid;
    cursor: pointer;
    font-size: 14px;
  }

  .blue-btn {

    &.active,
    &:hover {
      color: #007bff;
    }
  }

  .red-btn {

    &.active,
    &:hover {
      color: #dc3545;
    }
  }

  .yellow-btn {

    &.active,
    &:hover {
      color: #f0ad4e;
    }
  }

  @media screen and (max-width: 1100px) {
    position: relative;
    top: 0;
    left: 0;
    right: 0;

    .article-tool-box {
      flex-direction: row;
    }
  }
}
</style>
